package com.educate.common.exception;

import com.educate.common.api.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author yjj
 * @Description 全局异常处理
 * @createTime 2021/09/06
 */

@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 通用异常处理
     * @param e
     * @return
     */
       @ResponseBody
    @ExceptionHandler(value = {DefinitionException.class})
    public Result handle(DefinitionException e){
        if(e.getErrorCode() != null){
            log.error(e.getMessage(),e);
            return Result.failed(e.getErrorCode());
        }
        return Result.failed(e.getMessage());
    }

    /**
     * 其他异常处理
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = {Exception.class})
    public Result handle(Exception e){
        log.error(e.getMessage(),e);
        return Result.failed(e.getMessage());
    }

    /**
     * 实体校验异常处理
     * @param e
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    public Result handle(MethodArgumentNotValidException e){
        log.info(e.getMessage(),e);
        BindingResult bindingResult = e.getBindingResult();
        ObjectError objectError = bindingResult.getAllErrors().stream().findFirst().get();
        return Result.failed(objectError.getDefaultMessage());
    }



}
